﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

    public class FileLogger
    {
        #region Instance
        private static object logLock = new object();

        //private static FileLogger _instance;

        private string logFileName;
        public FileLogger(string logName)
        {
            logFileName = logName;
        }


        #endregion

        /// <summary>
        /// Write log to log file
        /// </summary>
        /// <param name="logContent">Log content</param>
        /// <param name="logType">Log type</param>
        public void WriteLog(string logContent, string logPerx = "")
        {
            try
            {
                string basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                if (!Directory.Exists(basePath + "\\Log"))
                {
                    Directory.CreateDirectory(basePath + "\\Log");
                }

                string dataString = DateTime.Now.ToString("yyyy-MM-dd");
                if (!Directory.Exists(basePath + "\\Log\\" + dataString))
                {
                    Directory.CreateDirectory(basePath + "\\Log\\" + dataString);
                }

                string[] logText = new string[] { DateTime.Now.ToString("hh:mm:ss") + ": " + logPerx + ": " + logContent };


                lock (logLock)
                {
                    File.AppendAllLines(basePath + "\\Log\\" + dataString + "\\" + logFileName, logText);
                }
            }
            catch (Exception) { }
        }

        public void WriteLog(byte[] logcontent, int start, int end, string logperx = "")
        {
            StringBuilder sb = new StringBuilder();
            var end2 = Math.Min(end, logcontent.Length);
            for (int i = start; i < end2; i++)
            {
                sb.Append(logcontent[i].ToString());
                sb.Append(",");
            }
            WriteLog(sb.ToString(), logperx);
        }

    }
